package com.junmeng.libadapter.databinding;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.junmeng.libadapter.base.BaseBindView;
import com.junmeng.libadapter.base.BindViewStore;
import com.junmeng.libadapter.base.IBindViewManager;
import com.junmeng.libadapter.utils.BindViewKeyUtil;

import java.util.List;

public class DataBindingBindViewManager<T, VDB extends ViewDataBinding> implements IBindViewManager<T, DataBindingViewHolder<VDB>, BaseDataBindingBindView<T, VDB>> {
    protected BindViewStore<Integer, BaseDataBindingBindView<T, VDB>> bindViewStore = new BindViewStore<>();
    protected SparseArray<Integer> viewTypeMapLayoutRes = new SparseArray<>();

    @Override
    public DataBindingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        ViewDataBinding binding = DataBindingUtil.inflate(inflater, viewTypeMapLayoutRes.get(viewType), parent, false);
        return new DataBindingViewHolder((RecyclerView) parent, binding);
    }

    @Override
    public void onBindViewHolder(@NonNull DataBindingViewHolder<VDB> holder, int position, @NonNull T t, @NonNull List<Object> payloads) {
        bindViewStore.getBindView(getBindViewKey(t)).bindViewData(holder, position, t, payloads);
    }

    @Override
    public void onViewRecycled(@NonNull DataBindingViewHolder<VDB> holder, @NonNull T t) {
        BaseBindView bindView = bindViewStore.getBindView(getBindViewKey(t));
        if (bindView == null) {
            return;
        }
        bindView.onViewRecycled(holder);
    }

    @Override
    public void register(@NonNull BaseDataBindingBindView bindView) {
        bindViewStore.putBindView(BindViewKeyUtil.getKey(bindView.itemBeanType), bindView);
    }

    @Override
    public int getItemViewType(int position, @NonNull T t) {
        int viewType = getBindViewKey(t);
        BaseDataBindingBindView baseDataBindingBindView = bindViewStore.getBindView(viewType);
        if (baseDataBindingBindView == null) {
            throw new RuntimeException("Don't forget to register " + t.getClass() + " before using");
        }
        int resId = baseDataBindingBindView.getItemLayoutResId(t);
        viewTypeMapLayoutRes.put(viewType, resId);
        return viewType;
    }

    private int getBindViewKey(@NonNull T t) {
        return BindViewKeyUtil.getKey(t.getClass());
    }

}
